package com.itcc.controller;

import com.itcc.entity.PageBean;
import com.itcc.entity.Product;
import com.itcc.entity.User;
import com.itcc.service.ProductService;
import com.itcc.service.BrowseService;
import com.itcc.service.impl.ProductServiceImpl;
import com.itcc.service.impl.BrowseServiceImpl;
import com.itcc.utils.Constants;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;


@WebServlet("/product")

public class ProductController extends BaseServlet{
    public String show(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {

        String tid=request.getParameter("tid");

        int pageSize=6;
        String currentPage = request.getParameter("currentPage");
        int page=1;
        if(currentPage!=null){
            page=Integer.parseInt(currentPage);
        }

        ProductService productService=new ProductServiceImpl();
        PageBean<Product> pageBean= productService.findPage(tid,page,pageSize);

        request.setAttribute("pageBean",pageBean);
        return Constants.FORWARD+"/goodsList.jsp";
    }
    public String detail(HttpServletRequest request,HttpServletResponse response) throws SQLException {

        String pid=request.getParameter("pid");
        String uid=request.getParameter("uid");

        ProductService productService=new ProductServiceImpl();
        Product product=productService.findProductByPid(pid);

        BrowseService browseService =new BrowseServiceImpl();
        browseService.saveRecord(uid,pid);
        request.setAttribute("product",product);

        return Constants.FORWARD+"/goodsDetail.jsp";
    }

    // 商品目录管理
    public String manage(HttpServletRequest request, HttpServletResponse response) throws SQLException {

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");

        if (user == null || user.getUrole()==0) {
            request.setAttribute("msg", "您没有权限访问管理页面");
            return Constants.FORWARD + "/index.jsp"; // 重定向到错误页面
        }


        ProductService productService = new ProductServiceImpl();

        List<Product> productList = productService.findAllProducts();

        request.setAttribute("productList", productList);

        return Constants.FORWARD + "/manageProducts.jsp";
    }

    //添加商品
    public String add(HttpServletRequest request, HttpServletResponse response) {
        try {
            Product product = new Product();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(request);
            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    // 处理文件上传
                    String fileName = item.getName();
                    if (fileName != null && !fileName.isEmpty()) {
                        // 保存文件到服务器
                        // 使用绝对路径来保存图片
                        String uploadPath = "D:\\ccshop\\src\\main\\webapp\\image";
                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs(); // 创建多级目录
                        }
                        File uploadedFile = new File(uploadDir, fileName);
                        item.write(uploadedFile);
                        // 更新产品图片路径，注意这里应该是相对Web应用根目录的路径
                        product.setPimage("image/" + fileName); // 注意路径前缀
                    } else {
                        // 如果没有选择图片，可以设置默认图片或进行错误处理
                        product.setPimage("default_image_path"); // 设置默认图片路径或错误处理
                    }
                } else {
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString("UTF-8");
                    // 使用 switch 语句或其他逻辑来确保字段名正确处理
                    switch (fieldName) {
                        case "pname":
                            product.setPname(fieldValue);
                            break;
                        case "pprice":
                            product.setPprice(new BigDecimal(fieldValue));
                            break;
                        case "pinfo":
                            product.setPinfo(fieldValue);
                            break;
                        case "ptype": // 处理商品类型
                            product.setTid(Integer.parseInt(fieldValue));
                            break;
                        default:
                            // 处理未知字段或错误
                            System.out.println("Unknown field: " + fieldName);
                            break;
                    }
                }
            }
            product.setPstate(0); // 假设所有新商品的初始状态都是0

            ProductService productService = new ProductServiceImpl();
            productService.addProduct(product);
            return Constants.REDIRECT +  "/ccshop/product?method=manage"; // 重定向到商品管理页面
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("msg", "添加商品失败");
            return Constants.FORWARD + "/error.jsp"; // 错误页面
        } catch (UnsupportedEncodingException | FileUploadException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 删除商品
    public String delete(HttpServletRequest request, HttpServletResponse response) {

        String pid = request.getParameter("pid");
        try {
            ProductService productService=new ProductServiceImpl();
            productService.deleteProduct(pid);
            return Constants.REDIRECT  +  "/ccshop/product?method=manage"; // 重定向到商品管理页面
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("msg", "删除商品失败");
            return Constants.FORWARD + "/error.jsp"; // 错误页面
        }
    }

    // 更新商品
    public String update(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        Product product = new Product();
        Map<String, String[]> parameterMap = new HashMap<>();
        boolean change = false;

        // 设置请求字符编码
        request.setCharacterEncoding("UTF-8");
        DateConverter converter = new DateConverter();
        converter.setPattern(new String("yyyy-MM-dd"));
        ConvertUtils.register(converter, Date.class);
        if (ServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                List<FileItem> items = upload.parseRequest(request);
                for (FileItem item : items) {
                    if (!item.isFormField()) {
                        // 处理文件上传
                        String fileName = item.getName();
                        if (fileName != null && !fileName.isEmpty()) {
                            // 保存文件到服务器
                            // 使用绝对路径来保存图片
                            String uploadPath = "D:\\ccshop\\src\\main\\webapp\\image";
                            File uploadDir = new File(uploadPath);
                            if (!uploadDir.exists()) {
                                uploadDir.mkdirs(); // 创建多级目录
                            }
                            File uploadedFile = new File(uploadDir, fileName);
                            item.write(uploadedFile);
                            // 更新产品图片路径，注意这里应该是相对Web应用根目录的路径
                            product.setPimage("image/" + fileName); // 注意路径前缀
                            change = true;
                        }  else {
                            // 如果没有选择新图片，使用旧图片路径
                            // 在这里不需要设置 pimage，因为会在后面统一处理
                        }
                    } else {
                        // 处理普通表单字段
                        String fieldName = item.getFieldName();
                        String fieldValue = item.getString("UTF-8"); // 明确指定字符编码
                        parameterMap.put(fieldName, new String[]{fieldValue});
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // 如果不是 multipart 请求，则使用传统方式获取参数
            parameterMap = request.getParameterMap();
        }


        // 先获取旧图片路径
        String oldPimage = parameterMap.get("oldPimage") != null ? parameterMap.get("oldPimage")[0] : null;

        try {
            // 使用 BeanUtils 填充对象，除了 pimage
            BeanUtils.populate(product, parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 根据是否有新图片来设置 pimage
        product.setPimage(change ? product.getPimage() : oldPimage);

        ProductService productService = new ProductServiceImpl();
        productService.updateProduct(product);

        return Constants.REDIRECT + "/ccshop/product?method=manage"; // 重定向到商品管理页面
    }
}
